package main

import (
	"google.golang.org/grpc"
	"io"
	"log"
	"net"
	pd "zt/go-study/grpc/proto"
)

const (
	PORT = "9002"
)

var _ pd.StreamServiceServer = (*StreamService)(nil)

type StreamService struct {
	pd.UnimplementedStreamServiceServer
}

// List 服务器端流式 RPC
func (s *StreamService) List(r *pd.StreamRequest, stream pd.StreamService_ListServer) error {
	for n := 0; n <= 6; n++ {
		err := stream.Send(
			&pd.StreamResponse{
				Pt: &pd.StreamPoint{
					Name:  r.Pt.Name,
					Value: r.Pt.Value + int32(n),
				},
			})
		if err != nil {
			return err
		}
	}

	return nil
}

// Record 客户端流式 RPC
func (s *StreamService) Record(stream pd.StreamService_RecordServer) error {
	for {
		r, err := stream.Recv()
		if err == io.EOF {
			return stream.SendAndClose(&pd.StreamResponse{Pt: &pd.StreamPoint{
				Name: "gRPC Stream Server: Record", Value: 1,
			}})
		}
		if err != nil {
			return err
		}
		log.Printf("stream.Recv pt.name: %s, pt.value: %d", r.Pt.Name, r.Pt.Value)
	}

	return nil
}

// Route 双向流式 RPC
func (s *StreamService) Route(stream pd.StreamService_RouteServer) error {
	n := 0
	for {
		err := stream.Send(&pd.StreamResponse{Pt: &pd.StreamPoint{
			Name:  "grpc Stream Client: Route",
			Value: int32(n),
		}})
		if err != nil {
			return err
		}

		r, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		n++

		log.Printf("stream.Recv pt.name: %s, pt.value: %d", r.Pt.Name, r.Pt.Value)
	}
	return nil
}

func main() {
	server := grpc.NewServer()
	pd.RegisterStreamServiceServer(server, &StreamService{})

	lis, err := net.Listen("tcp", ":"+PORT)
	if err != nil {
		log.Fatalf("net.Listen err: %v", err)
	}

	server.Serve(lis)
}
